<template>
  <div id="app">
    <div id="up_div">
      <div class="app-container">
        <divider title="移库单基本信息"></divider>
        <el-divider></el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="移库单号">
                <el-input v-model="form.transferOrderNo" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="移库类型">
                <el-radio-group v-model="form.transferType" >
                  <el-radio-button
                    v-for="item in dict.type.wms_transfer_type"
                    :key="item.value"
                    :label="item.value"
                  >
                    {{ item.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="原仓库" prop="sourceWarehouseId">
                <el-select v-model="form.sourceWarehouseId" @change=setSourceWarehouseAreaSelect placeholder="请选择原仓库" style="width: 65%" >
                  <el-option v-for="item in this.warehouseSelect" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="原库区"  prop="sourceWarehouseAreaId">
                <el-select v-model="form.sourceWarehouseAreaId" @change=setSourceWarehouseRackSelect placeholder="请选择原库区" style="width: 65%" :disabled="!form.sourceWarehouseId">
                  <el-option v-for="item in this.warehouseAreaSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="原货架" prop="sourceWarehouseRackId">
                <el-select v-model="form.sourceWarehouseRackId" @change=setSourceWarehouseLocationSelect placeholder="请选择原货架" style="width: 65%" :disabled="!form.sourceWarehouseAreaId">
                  <el-option v-for="item in this.warehouseRackSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="原货位" prop="sourceWarehouseLocationId">
                <el-select v-model="form.sourceWarehouseLocationId" placeholder="请选择原货位" style="width: 65%" :disabled="!form.sourceWarehouseRackId">
                  <el-option v-for="item in this.warehouseLocationSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="目标仓库" prop="targetWarehouseId">
                <el-select v-model="form.targetWarehouseId" @change=setTargetWarehouseAreaSelect placeholder="请选择目标仓库" style="width: 65%" >
                  <el-option v-for="item in this.warehouseSelect" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="目标库区"  prop="targetWarehouseAreaId">
                <el-select v-model="form.targetWarehouseAreaId" @change=setTargetWarehouseRackSelect placeholder="请选择目标库区" style="width: 65%" :disabled="!form.targetWarehouseId">
                  <el-option v-for="item in this.warehouseAreaSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="目标货架" prop="targetWarehouseRackId">
                <el-select v-model="form.targetWarehouseRackId" @change=setTargetWarehouseLocationSelect placeholder="请选择目标货架" style="width: 65%" :disabled="!form.targetWarehouseAreaId">
                  <el-option v-for="item in this.warehouseRackSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="目标货位" prop="targetWarehouseLocationId">
                <el-select v-model="form.targetWarehouseLocationId" placeholder="请选择目标货位" style="width: 65%" :disabled="!form.targetWarehouseRackId">
                  <el-option v-for="item in this.warehouseLocationSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="24">

            <el-col :span="12">
              <el-form-item label="备注">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="form.remark">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数量">
                <el-input v-model="form.transferQuantity" disabled></el-input>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </div>
    </div>

    <div id="down_div">
      <div class="app-container">
        <divider title="商品明细"></divider>
        <el-divider></el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-tooltip :disabled="disabled" :content="tooltip" placement="right" effect="light" >
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="addWmsTransfer"
                v-hasPermi="['system:wmsInbound:add']" :disabled="!form.sourceWarehouseLocationId"
              >添加商品</el-button>
            </el-tooltip>
          </el-col>

        </el-row>
        <el-table
          :data="sublevelDataList"
          height="250"
          border
          style="width: 100%">
          <el-table-column
            prop="productName"
            label="商品名称"
            width="180">
          </el-table-column>
          <el-table-column label="入库单号" align="center" prop="inboundOrderNo" />
          <el-table-column label="入库时间" align="center" prop="createTime" />
          <el-table-column label="商品编码" align="center" prop="productCode" />
          <el-table-column label="规格型号" align="center" prop="productSpec" />
          <el-table-column label="单位" align="center" prop="productUnit" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_product_unit" :value="scope.row.productUnit">
              </dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="剩余库存" align="center" prop="totalQuantityMax"  >
            <template #default="scope">
              <span style="color: red">{{ scope.row.totalQuantityMax }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="unitPrice"
            align="center"
            label="单价">
          </el-table-column>
          <!-- 循环渲染多个可编辑列 -->
          <el-table-column
            v-for="column in editableColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            header-align="center"
          >
            <template #default="{ row, $index }">
              <el-input-number
                v-if="column.prop === 'totalAmount'"
                v-model="row[column.prop]"
                :precision="2"
                :min="1"
                disabled
                :placeholder="'请输入' + column.label"
              ></el-input-number>

              <!-- 当字段是 totalQuantity 时使用不带精度的输入框 -->
              <el-input-number
                v-else-if="column.prop === 'totalQuantity'"
                v-model="row[column.prop]"
                :min="1"
                :max="row.totalQuantityMax"
                @change="(val) => calculateAmount(row, val)"
                :placeholder="'请输入' + column.label"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:wmsInbound:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div id="foot_div">
      <div class="button-group">
        <el-button type="primary" icon="el-icon-plus" @click="handleSubmit">完成移库</el-button>
        <el-button type="warning" @click="handleSaveTemp">暂存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </div>
    <EditWmsOutboundList ref="AddWmsOutboundList" @goBlackParent="sublevelData"></EditWmsOutboundList>
  </div>
</template>
<script>

import divider from "@/components/divider/index.vue";
import EditWmsOutboundList from "@/views/system/wmsOutbound/model/editWmsOutboundList.vue";
import {
  getSupplierSelect, getWarehouseAreaSelect,
  getWarehouseAreaSelectByWarehouseId, getWarehouseRackSelect,
  getWarehouseRackSelectWarehouseAreaId, getWarehouseSelect, getWmsWarehouseLocationSelect,
  getWmsWarehouseLocationSelectByRackId
} from "@/api/system/selectVo";
import {clearOrderNo} from "@/api/system/wmsOutbound";
import {updateWmsTransfer} from "@/api/system/wmsTransfer";

export default {
  name: "EditWmsTransfer",
  props: {
    wmsTransfer: {}
  },
  components: { divider,EditWmsOutboundList},
  dicts:["wms_transfer_type","wms_product_unit"],
  data(){
    return{
      form:{
        transferOrderNo:"",
        transferType:1,
        remark: '',
        totalAmount: 0,
        totalQuantity: 0,
        sourceWarehouseId: null,
        sourceWarehouseAreaId: null,
        sourceWarehouseRackId: null,
        sourceWarehouseLocationId: null,
        sourceWarehouseLabel: null,
        sourceWarehouseAreaLabel: null,
        sourceWarehouseRackLabel: null,
        sourceWarehouseLocationLabel: null,
        targetWarehouseId: null,
        targetWarehouseAreaId: null,
        targetWarehouseRackId: null,
        targetWarehouseLocationId: null,
        supplierId: null,
        orderNo: null,
        transferQuantity: 0,
        inventoryHistoryList: [],
      },
      select:[],
      disabled: false,
      load: false,
      tooltip: "请完善仓库、库区、货架、货位信息",
      tableData: [],
      editableColumns: [
        { prop: 'totalQuantity', label: '数量', width: '250' },
        { prop: 'totalAmount', label: '金额', width: '250' }
      ],
      warehouseSelect:[],
      warehouseAreaSelect:[],
      warehouseRackSelect:[],
      warehouseLocationSelect:[],
      warehouseSupplierSelect:[],
      sublevelDataList:[],

      // 表单校验
      rules: {
        sourceWarehouseId: [
          { required: true, message: "原仓库不能为空", trigger: "blur" }
        ],
        sourceWarehouseAreaId: [
          { required: true, message: "原库区不能为空", trigger: "change" }
        ],
        sourceWarehouseRackId: [
          { required: true, message: "原货架不能为空", trigger: "change" }
        ],
        sourceWarehouseLocationId: [
          { required: true, message: "原货位不能为空", trigger: "change" }
        ],
        targetWarehouseId: [
          { required: true, message: "目标仓库不能为空", trigger: "blur" }
        ],
        targetWarehouseAreaId: [
          { required: true, message: "目标库区不能为空", trigger: "change" }
        ],
        targetWarehouseRackId: [
          { required: true, message: "目标货架不能为空", trigger: "change" }
        ],
        targetWarehouseLocationId: [
          { required: true, message: "目标货位不能为空", trigger: "change" }
        ],
      },
    }
  },
  watch: {
    'form.sourceWarehouseRackId'(newVal) {
      if (this.form.sourceWarehouseLocationId!=null){
        this.disabled = true;
      }else {
        this.sublevelDataList = [];
        this.form.transferQuantity=0;
        this.disabled = false;
      }
    },
  },
  created() {
    this.getWarehouseSelect();
    this.getSupplierSelect();
    this.getWarehouseAreaSelect();
    this.getWarehouseRackSelect();
    this.getWmsWarehouseLocationSelect();

    this.form = this.wmsTransfer;

    this.sublevelDataList = this.wmsTransfer.inventoryHistoryList;

    this.sublevelDataList.forEach(item => {
      item.totalQuantityMax = (item.totalQuantityMax || 0) + (item.totalQuantity || 0);
    });
  },
  methods: {
    getWarehouseSelect(){
      getWarehouseSelect().then(response => {
        this.warehouseSelect = response.data;
      })
    },
    getSupplierSelect(){
      getSupplierSelect().then(response => {
        this.warehouseSupplierSelect = response.data;
      })
    },


    getWarehouseAreaSelect(){
      getWarehouseAreaSelect().then(response => {
        this.warehouseAreaSelect = response.data;
      })
    },
    getWarehouseRackSelect(){
      getWarehouseRackSelect().then(response => {
        this.warehouseRackSelect = response.data;
      })
    },
    getWmsWarehouseLocationSelect(){
      getWmsWarehouseLocationSelect().then(response => {
        this.warehouseLocationSelect = response.data;
      })
    },

    handleSubmit(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.sublevelDataList.length>0){
            this.load=true;
            this.form.inventoryHistoryList=this.sublevelDataList
            this.form.transferStatus="1"
            updateWmsTransfer(this.form).then( response => {
              this.$message.success('移库成功');
              this.load=false;
              this.$emit('handleCancel');
            })
          }else {
            this.$message.warning('请添加商品明细！');
          }
        }
      })
    },
    handleSaveTemp(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.sublevelDataList.length>0){
            this.load=true;
            this.form.inventoryHistoryList=this.sublevelDataList
            this.form.transferStatus="2"
            updateWmsTransfer(this.form).then( response => {
              this.$message.success('已暂存');
              this.load=false;
              this.$emit('handleCancel');
            })
          }else {
            this.$message.warning('请添加商品明细！');
          }
        }
      })
    },
    handleCancel(){
      clearOrderNo().then( response =>{
        this.$emit("handleCancel")
      })
    },
    //添加商品明细
    addWmsTransfer(){
      this.getLabelByValue();
      var queryParam = {
        warehouseId:null,
        warehouseAreaId:null,
        warehouseRackId:null,
        warehouseLocationId:null,
        warehouseLabel:null,
        warehouseAreaLabel:null,
        warehouseRackLabel:null,
        warehouseLocationLabel:null,
      };
      queryParam.warehouseId = this.form.sourceWarehouseId;
      queryParam.warehouseAreaId = this.form.sourceWarehouseAreaId;
      queryParam.warehouseRackId = this.form.sourceWarehouseRackId;
      queryParam.warehouseLocationId = this.form.sourceWarehouseLocationId;
      queryParam.warehouseLabel = this.form.sourceWarehouseLabel;
      queryParam.warehouseAreaLabel = this.form.sourceWarehouseAreaLabel;
      queryParam.warehouseRackLabel = this.form.sourceWarehouseRackLabel;
      queryParam.warehouseLocationLabel = this.form.sourceWarehouseLocationLabel;
      this.$refs.AddWmsOutboundList.show(queryParam)
    },

    handleDelete(row){
      this.$modal.confirm('是否确认删除商品的数据项？').then(function() {
      }).then(() => {
        // this.getList()
        this.deleteTableData(row.inboundId);
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    deleteTableData(inboundId){
      for(var i=0;i<this.sublevelDataList.length;i++){
        if(this.sublevelDataList[i].inboundId === inboundId) {
          this.sublevelDataList.splice(i, 1);  // 删除当前元素
          i--;  // 因为数组长度减少了，需要将索引减1
        }
      }
      this.computedData();
    },


    // 子级传过来的数据
    sublevelData(data) {
      // 如果sublevelDataList为空，直接初始化
      if (!this.sublevelDataList || this.sublevelDataList.length === 0) {
        this.sublevelDataList = data.map(item => ({
          ...item,
          totalAmount: item.purchasePrice,
          unitPrice: item.purchasePrice,
          totalQuantity: 1,
          totalQuantityMax: item.totalQuantity,
          id: null,
          inboundId: item.id,
        }));
      } else {
        // 如果sublevelDataList已有数据，进行合并处理
        data.forEach(newItem => {
          // 查找是否已存在相同产品
          const existingItem = this.sublevelDataList.find(
            existing => existing.inboundId === newItem.id
          );

          if (existingItem) {
            // 如果存在相同产品，累加数量并更新金额
            existingItem.totalQuantity += 1;
            existingItem.totalAmount = existingItem.unitPrice * existingItem.totalQuantity;
          } else {
            // 如果不存在，添加新条目
            this.sublevelDataList.push({
              ...newItem,
              totalAmount: newItem.purchasePrice,
              unitPrice: newItem.purchasePrice,
              totalQuantity: 1,
              id: null,
              totalQuantityMax: newItem.totalQuantity,
              inboundId: newItem.id,
            });
          }
        });
      }

      this.computedData();
    },
    //计算商品明细的金额和数量
    computedData(){
      let totalQuantity = 0;
      let totalAmount = 0;
      this.sublevelDataList.forEach(item => {
        totalQuantity += Number(item.totalQuantity) || 0;
        totalAmount += Number(item.totalAmount) || 0;
      });

      this.form.totalAmount=totalAmount;
      this.form.transferQuantity=totalQuantity;
    },
    //商品明细根据改编数量来改变金额和总金额和总数量
    calculateAmount(row, quantity) {
      row.totalAmount = parseFloat((quantity * row.unitPrice).toFixed(2))

      this.computedData();

    },
    getLabelByValue() {
      const warehouse = this.warehouseSelect.find(item => item.value === this.form.sourceWarehouseId);
      this.form.sourceWarehouseLabel = warehouse ? warehouse.label : '未知仓库';
      const warehouseArea = this.warehouseAreaSelect.find(item => item.value === this.form.sourceWarehouseAreaId);
      this.form.sourceWarehouseAreaLabel = warehouseArea ? warehouseArea.label : '未知库区';
      const warehouseRack = this.warehouseRackSelect.find(item => item.value === this.form.sourceWarehouseRackId);
      this.form.sourceWarehouseRackLabel = warehouseRack ? warehouseRack.label : '未知货架';
      const warehouseLocation = this.warehouseLocationSelect.find(item => item.value === this.form.sourceWarehouseLocationId);
      this.form.sourceWarehouseLocationLabel = warehouseLocation ? warehouseLocation.label : '未知货位';
    },
    setSourceWarehouseAreaSelect() {
      this.form.sourceWarehouseAreaId=null;
      this.form.sourceWarehouseRackId=null;
      this.form.sourceWarehouseLocationId=null;
      getWarehouseAreaSelectByWarehouseId(this.form.sourceWarehouseId).then(response => {
        this.warehouseAreaSelect=response.data
      })
    },
    setSourceWarehouseRackSelect () {
      this.form.sourceWarehouseRackId=null;
      this.form.sourceWarehouseLocationId=null;
      if(this.form.sourceWarehouseAreaId){
        getWarehouseRackSelectWarehouseAreaId(this.form.sourceWarehouseAreaId).then(response => {
          this.warehouseRackSelect=response.data
        })
      }
    },
    setSourceWarehouseLocationSelect() {
      this.form.sourceWarehouseLocationId=null;
      if(this.form.sourceWarehouseRackId){
        getWmsWarehouseLocationSelectByRackId(this.form.sourceWarehouseRackId).then(response => {
          this.warehouseLocationSelect=response.data
        })
      }
    },
    setTargetWarehouseAreaSelect() {
      this.form.targetWarehouseAreaId=null;
      this.form.targetWarehouseRackId=null;
      this.form.targetWarehouseLocationId=null;
      getWarehouseAreaSelectByWarehouseId(this.form.targetWarehouseId).then(response => {
        this.warehouseAreaSelect=response.data
      })
    },
    setTargetWarehouseRackSelect () {
      this.form.targetWarehouseRackId=null;
      this.form.targetWarehouseLocationId=null;
      if(this.form.targetWarehouseAreaId){
        getWarehouseRackSelectWarehouseAreaId(this.form.targetWarehouseAreaId).then(response => {
          this.warehouseRackSelect=response.data
        })
      }
    },
    setTargetWarehouseLocationSelect() {
      this.form.targetWarehouseLocationId=null;
      if(this.form.targetWarehouseRackId){
        getWmsWarehouseLocationSelectByRackId(this.form.targetWarehouseRackId).then(response => {
          this.warehouseLocationSelect=response.data
        })
      }
    },
  }
}
</script>
<style scoped lang="scss">
body, html {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden; /* 防止整个页面滚动 */
}

#app {
  background-color: #ffffff;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 3px;
  display: flex;
  flex-direction: column;
  position: relative;
}

#up_div {
  background-color: white;
  height: 30%;
  width: 100%;
  margin-bottom: 20px;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  overflow-y: auto; /* 允许内容滚动 */
}

#down_div {
  background-color: white;
  flex: 1; /* 占据剩余空间 */
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border-radius: 4px;
  overflow-y: auto; /* 允许内容滚动 */
  margin-bottom: 60px; /* 为底部按钮留出空间 */
}

#foot_div {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.button-group {
  display: flex;
  gap: 20px;
}

.app-container {
  padding: 20px;
}
</style>
